<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
use App\Components\Tools;

use App\Models\DyModels\Douyin;
use App\Models\VoidsModels\CommentKey;
/**
 * 获取抖音视频评论
 */
class DyKeywordVideoComment extends Command{
  /**
   * The name and signature of the console command.
   *
   * @var string
   */
  protected $signature = 'DyKeywordVideoComment';

  /**
   * The console command description.
   *
   * @var string
   */
  protected $description = '获取抖音视频评论';
  
  
  protected $thirsdUrlMe="http://139.186.147.106:5000/comment";	//自用的服务器评论接口地址
  protected $thirsdUrl="http://api.xstatus.cn/douyin/video/comments?token=3440488a80744d30abe1a41f3a7062d5&aweme_id=";	//第三方评论接口
  
  /**
   * Execute the console command.
   *
   * @return mixed
   */
  public function handle(){
    //$this->getDyKeywordVideoComment();
    Tools::commandsLog('DyKeywordVideoComment_begin:'.date("Y-m-d H:i:s"));
     $this->getComment();
    Tools::commandsLog('DyKeywordVideoComment_end:'.date("Y-m-d H:i:s")); 
  }
  
  
  
  //视频评论抓取-----------------------------------------------------------------------------------------------------------------------------------------------------
	//数据库读取需要抓评论的视频id
	function getComment(){
		set_time_limit(0);
		$video_comment=new Douyin();
		$video_list=$video_comment->videoIdAll();
		if($video_list){
			foreach($video_list as $key=>$val){
				$this->urlGetCommentMe($val['video_id'],0,$val['title'],$val['keyword']);
			}
		}
	}
	
	//自用视频评论抓取接口
	function urlGetCommentMe($videoId,$cursor,$title,$keyword){
		set_time_limit(0);
		$url=$this->thirsdUrlMe."?aweme_id={$videoId}&cursor={$cursor}&count=20";
		$api_msg_Arr['create_time']=date('Y-m-d H:i:s',time());//接口请求时间
		$data=$this->getWhileJson($url);
		$api_msg_Arr['receive_time']=date('Y-m-d H:i:s',time());//接口接收时间
		if( !$data || (isset($data['status']) && $data['status']=='error') || (isset($data['code']) && $data['code']==-1) ){
			$this->urlGetComment($videoId,$cursor,$title,$keyword);
		}elseif( isset($data['status']) && $data['status']=='success' && isset($data['code']) && $data['code']==200 && isset($data['data']['comments']) && $data['data']['comments'] ){
			// echo "<pre/>";print_r($data['data']['comments']);exit;
			$this->videoCommentList($data['data']['comments'],$title,$keyword);
			if( isset($data['data']['has_more']) && $data['data']['has_more']>0 ){
				$cursor=$cursor+20;
				$this->urlGetCommentMe($videoId,$cursor,$title,$keyword);
			}
		}else{
			$api_msg_Arr['type']=0;
			$api_msg_Arr['url']=$url;
			$api_msg_Arr['return']=json_encode($data);
			$video_comment=new Douyin();
			$video_comment->api_msg($api_msg_Arr);//把接口调用数据写入数据库 由先前那步转换成json数据
		}
	}
	
	// 外网第三方 api 接口 获取一级评论信息根据需要取出数据 入库
	function urlGetComment($videoId,$cursor,$title,$keyword){
		set_time_limit(0);
		$url=$this->thirsdUrl ."{$videoId}&cursor={$cursor}";
		$api_msg_Arr['create_time']=date('Y-m-d H:i:s',time());//接口请求时间
		$data=$this->getWhileJson($url,'',0,20);
		$api_msg_Arr['receive_time']=date('Y-m-d H:i:s',time());//接口接收时间
		// echo "<pre/>";print_r($data);exit;
		if(isset($data['status_code']) && $data['status_code']==0 && isset($data['x-status']) && $data['x-status'] ){
			if(isset($data['comments'][0])){
			    //获取数据然后入库 方法在下面直接调用
				$this->videoCommentList($data['comments'],$title,$keyword);
			}
			if(isset($data['has_more']) && $data['has_more']>0 ){
				$cursor=$cursor+20;//分页的？+20大概是因为一次只有20个数据 下一轮继续查询？
				$this->urlGetComment($videoId,$cursor,$title,$keyword);
			}
		}else{
			$api_msg_Arr['type']=0;
			$api_msg_Arr['url']=$url;
			$api_msg_Arr['return']=json_encode($data);
			$video_comment=new Douyin();
			$video_comment->api_msg($api_msg_Arr);//把接口调用数据写入数据库 由先前那步转换成json数据
		}
	}
	//存入评论
	function videoCommentList($commentList,$title,$keyword){
		$video_comment=new Douyin();
		foreach($commentList as $k=>$v){
			$text=isset($v['text']) ? $v['text'] : '';
			$signature=isset($v['user']['signature']) ? $v['user']['signature'] : '';
			$video_id=isset($v['aweme_id']) ? $v['aweme_id'] : '';		//视频id
			$comment_id=isset($v['cid']) ? $v['cid'] : '';				//评论id
			$rec_comment=isset($v['reply_comment_total']) ? intval($v['reply_comment_total']) : 0;		//回复数
			
			$findIn=$this->findk($text,$signature);
			$arr=array(
				'nickname'=>isset($v['user']['nickname']) ? htmlspecialchars($v['user']['nickname'],ENT_QUOTES) : '',
				'signature'=>htmlspecialchars($signature,ENT_QUOTES),
				'user_id'=>isset($v['user']['unique_id']) && !empty($v['user']['unique_id']) ? $v['user']['unique_id'] : ( isset($v['user']['short_id']) ? $v['user']['short_id'] : ''),
				'sec_uid'=>isset($v['user']['sec_uid']) ? $v['user']['sec_uid'] : '',
				'content'=>htmlspecialchars($text,ENT_QUOTES),
				'create_time'=>date('Y-m-d H:i:s',$v['create_time']),
				'update_time'=>date('Y-m-d H:i:s',time()),
				'pt_type'=>1,
				'userImg'=>isset($v['user']['avatar_medium']['url_list'][1]) ? $v['user']['avatar_medium']['url_list'][1] : $v['user']['avatar_medium']['url_list'][0],
				'video_url'=>isset($v['aweme_id']) ? "https://www.douyin.com/video/".$video_id : '',
				'birthday'=>isset($v['user']['birthday']) ? $v['user']['birthday'] : '',
				'rec_comment'=>$rec_comment,
				'digg_count'=>isset($v['digg_count']) ? intval($v['digg_count']) : 0,
				'title'=>htmlspecialchars($title,ENT_QUOTES),
				'keyword'=>$keyword,
				'tells'=>substr($findIn,5) ? substr($findIn,5) : '',
				'uid'=>isset($v['user']['uid']) ? $v['user']['uid'] : '',
			);
			if($findIn){
				$video_comment->saveVideoComment($arr,$video_id,$comment_id);
			}
			//二级评论
			// if($rec_comment>0){
				// $this->urlGetCommentMe($video_id,$comment_id,0,$title,$keyword);
			// }
		}
	}
	
	
	
	//查找是否存在需要的关键词 wx qq 电话号码
	function findk($text,$signature){
		$re=$this->findkeyword($text);
		if($re){
			$tells="tells";
			preg_match_all("/[a-z0-9_-]{6,20}/i",$signature,$signatureArr);
			if(isset($signatureArr[0][0])){
				$tells.=implode("\r\n",$signatureArr[0]);
			}
			return $tells;
		}
		return false;
	}
	//查找是否存在关键词
	function findkeyword($text){
		$CommentKey=new CommentKey();
		//$url=str_replace("/public",'',$_SERVER['DOCUMENT_ROOT']);
                $url=str_replace("/public",'',BASE_PATH);
		$keywords=json_decode(file_get_contents($url."/config/keywords.json"),true);
		$list=$CommentKey->getKey();
		
		if( !empty($text) && isset($keywords['keywords'][0]) ){
			foreach($keywords['keywords'] as $k=>$v){
				if(stristr($text,$v)){
					return $text;
				}
			}
		}
		
		if( !empty($text) && $list){
			foreach($list as $k=>$v){
				if(stristr($text,$v['name'])){
					return $text;
				}
			}
		}
		return false;
	}
	
	
	
	
	
	
	/**
	*	获取评论 get 请求 重试机制
	*	checkTest	需要正确匹配存在的字符串 否则 开启重试
	*	$retry		重试retry-1次	默认3次
	*	sleep		休眠时间 秒
	*/
	function getWhileJson($url,$checkTest='"status": "success", "code": 200,',$retry=4,$sleep=20){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_TIMEOUT,60);//连接后等待时间
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);//连接前等待时间
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//为true，则会跟踪爬取重定向页面，否则，不会跟踪重定向页面
		curl_setopt($ch, CURLOPT_ENCODING, "");//返回乱码处理
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		
		$output = curl_exec($ch);
		
		if($checkTest){
			while( !strpos($output,$checkTest) && --$retry > 0 ){
				sleep($sleep);
				$output = curl_exec($ch);
			}
		}
		
		curl_close($ch);
		return json_decode($output, true);
	}
  
  
  
//-------------------before
  
  
  public function getDyKeywordVideoComment(){
    $mtime= date("Y-m-d H:i:s", strtotime("-1 days"));
    //3天前的视频不再获取评论
    $data = DB::table('pt_keyword_video')->select('id','sec_item_id')->where('create_time','>',$mtime)->get();
    if(!empty($data)){
      foreach ($data as $key => $val){
        $this->saveData(0,10,$val);
      }
    }
  }
  
  public function saveData($cursor,$count,$keywordVideo){
    $result = \App\Components\DyTools::videoSearchComment($cursor,$keywordVideo['sec_item_id'],$count);
    if($result['error_code'] == 0){
      if(!empty($result['list'])){
        foreach($result['list'] as $val){
          $this->dyKeywordVideoComment($val,$keywordVideo);
        }
      }
      if($result['has_more']){//如果还有更多
        $cursor++;
        $this->saveData($cursor,$keywordVideo['sec_item_id'],$count);
      }
    }
  }
  
  public function dyKeywordVideoComment($val,$keywordVideo){
    $oKeywordVideoComment = new \App\Models\DyModels\KeywordVideoComment();
    $kvData = $oKeywordVideoComment->db_get(['comment_id'=>['=',$val['comment_id']],'keyword_video_id'=>['=',$keywordVideo['id']]]);
    $data = [];
    $data['digg_count'] = $val['digg_count'];
    $data['reply_comment_total'] = $val['reply_comment_total'];
    $data['top'] = $val['top'] ? 1 : 0;
    $data['comment_id'] = $val['comment_id'];
    $data['comment_user_id'] = $val['comment_user_id'];
    $data['content'] = $val['content'];
    $data['update_time'] = date('Y-m-d H:i:s');
    if(!empty($kvData)){
      $oKeywordVideoComment->db_update('',$kvData['id'],$data);
    }else{
      $data['keyword_video_id'] = $keywordVideo['id'];
      $data['sec_item_id'] = $keywordVideo['sec_item_id'];
      $data['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
      $oKeywordVideoComment->db_insert($data);
    }
  }
}
